package com.yuncheng.oaApi.FlowController;

import cn.hutool.core.collection.CollectionUtil;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.oaApi.constant.OaCommonFlowConstant;
import com.yuncheng.oaApi.constant.OaFlowNodeConstant;
import com.yuncheng.oaApi.constant.OaFlowConstant;
import com.yuncheng.oaApi.vo.DyFlowVo;
import com.yuncheng.oaApi.vo.OaReturnVo;
import com.yuncheng.oaApi.vo.Result;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.oaApi.FlowService.NewPartyRsDyrdsqjlFlowService;
import com.yuncheng.annotation.AutoLog;
import com.yuncheng.oaApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.oaApi.service.*;
import com.yuncheng.spcyApi.utils.DateConvert;
import com.yuncheng.oaApi.utils.GetUuIdUtils;
import com.yuncheng.utils.ThreadContextHelper;
import com.yuncheng.vo.*;
import groovy.lang.Lazy;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;



@Api(tags = "NEW_DW-申请入党流程")
@RestController
@RequestMapping("/api/spzx-oa/dw_sqrd")
public class NewPartyRsDyrdsqjlFlowController {
    private static final Logger log = LoggerFactory.getLogger(NewPartyRsDyrdsqjlFlowController.class);

    @Resource
    private IOaSpcySqsxJobService spcySqsxJobService;

    @Resource
    private IOaYcSysUserService ycSysUserService;

    @Resource
    @Lazy
    private IOaSysTzMessageService sysTzMessageService;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    @Resource
    @Lazy
    private IOaProcessBusinessService oaProcessBusinessService;

    @Resource
    @Lazy
    private IPartyRsDyrdsqjlService partyRsDyrdsqjlService;

    @Resource
    @Lazy
    private NewPartyRsDyrdsqjlFlowService newPartyRsDyrdsqjlFlowService;

    @Resource
    @Lazy
    private IPartyRsDyfzgcjlService partyRsDyfzgcjlService;

    @Resource
    @Lazy
    private IOaFjzykEntityService oaFjzykService;

    @AutoLog(value = "申请入党前确认")
    @ApiOperation(value = "申请入党前确认")
    @GetMapping(value = "verifyDy")
    public HttpResult<?> verifyDy(){
        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        String fuserid = user.getId();

        YcSysUser ycSysUser = ycSysUserService.getById(fuserid);

        List<Object> DyList = new ArrayList();
        HttpResult httpResult = new HttpResult();
        if (StringUtils.isBlank(ycSysUser.getFzzmm())){
            throw new BusinessException("请确定本人政治面貌");
        }

        if (ycSysUser.getFzzmm().equals(OaFlowConstant.ZZMM_ZGDY) || ycSysUser.getFzzmm().equals(OaFlowConstant.ZZMM_ZGGCDDY)){
            //如果已经是共产党员

            List<PartyRsDyrdsqjl> partyRsDyrdsqjls = partyRsDyrdsqjlService.list(new LambdaQueryWrapper<PartyRsDyrdsqjl>()
                    .eq(PartyRsDyrdsqjl::getFuserid, fuserid));
            if (CollectionUtils.isEmpty(partyRsDyrdsqjls)){
                httpResult.setSuccess(false);
                httpResult.setCode(200);
                httpResult.setMessage("没有查询到入党申请记录，请联系人事补录");
                httpResult.setResult(partyRsDyrdsqjls);
                return httpResult;
            }

            DyList = Collections.singletonList(partyRsDyfzgcjlService.list(new LambdaQueryWrapper<PartyRsDyfzgcjl>()
                    .eq(PartyRsDyfzgcjl::getFrdsqjlid, partyRsDyrdsqjls.get(0).getId())));
            if (CollectionUtils.isNotEmpty(DyList)){
                httpResult.setSuccess(false);
                httpResult.setCode(200);
                httpResult.setMessage("您已是正式党员，请勿重复申请入党");
                httpResult.setResult(DyList);
                return httpResult;
            }
        }else {
            List<PartyRsDyrdsqjl> partyRsDyrdsqjls = partyRsDyrdsqjlService.list(new LambdaQueryWrapper<PartyRsDyrdsqjl>()
                    .eq(PartyRsDyrdsqjl::getFuserid, fuserid)
                    .eq(PartyRsDyrdsqjl::getFlczt, OaFlowNodeConstant.HJMC_LCZB));
            if (CollectionUtils.isNotEmpty(partyRsDyrdsqjls)){
                httpResult.setSuccess(false);
                httpResult.setCode(200);
                httpResult.setMessage("已存在申请中的入党申请！");
                httpResult.setResult(partyRsDyrdsqjls);
                return httpResult;
            }else {
                httpResult.setMessage("当前没有申请入党记录，可以申请入党！");
                return httpResult;
            }
        }
        return httpResult;
    }


    @AutoLog(value = "查询当前用户的党员发展记录")
    @ApiOperation(value = "查询当前用户的党员发展记录")
    @GetMapping(value = "selectdyfzjl")
    public HttpResult<?> selectdyfzjl (String frdsqjlid, String hjmc,
                                       @RequestParam(value = "jobid",defaultValue = "") String jobid){
        if (StringUtils.isBlank(frdsqjlid)){
            throw new BusinessException("参数不存在！");
        }
        if (StringUtils.isBlank(hjmc)){
            throw new BusinessException("环节参数不存在！");
        }
        PartyRsDyfzgcjl dy = null;
        String pid = "";
        boolean isEmptyData = true;
        List<OaFjzykEntity> fjList = new ArrayList<>();

        // 是否重复环节
        boolean isDuplicateName = false;
        if (hjmc.equals(OaFlowConstant.DF_HJMC_ZBDHTL23_1)){
            hjmc = OaFlowConstant.DF_HJMC_ZBDHTL23;
            isDuplicateName = true;
        }
        if (hjmc.equals(OaFlowConstant.DF_HJMC_SJDWSP24_2)){
            hjmc = OaFlowConstant.DF_HJMC_SJDWSP24;
            isDuplicateName = true;
        }

        List<PartyRsDyfzgcjl> list = partyRsDyfzgcjlService.list(new LambdaQueryWrapper<PartyRsDyfzgcjl>()
                 .eq(PartyRsDyfzgcjl::getFrdsqjlid, frdsqjlid)
                 .eq(PartyRsDyfzgcjl::getFbzmc, hjmc)
                 .orderByDesc(PartyRsDyfzgcjl::getCreateTime));
        if (CollectionUtil.isNotEmpty(list)){

            if (StringUtils.isBlank(jobid)){
                if (isDuplicateName && list.size()>1){
                    dy = list.get(0);
                    pid = list.get(0).getJobid();
                    isEmptyData = false;
                }

                if (isDuplicateName){
                    if (list.size()>1){

                        dy = list.get(0);
                        pid = list.get(0).getJobid();
                        isEmptyData = false;
                    }
                }else {
                    dy = list.get(0);
                    pid = list.get(0).getJobid();
                    isEmptyData = false;
                }

            }else {
                if (StringUtils.isNotBlank(list.get(0).getJobid()) && jobid.equals(list.get(0).getJobid())){
                    dy = list.get(0);
                    pid = list.get(0).getJobid();
                    isEmptyData = false;
                }
            }
        }

        // 是否为空数据
        if (isEmptyData){
            dy = new PartyRsDyfzgcjl();
            pid = "0";
        }
        dy.setId(frdsqjlid);

        fjList = oaFjzykService.list(new LambdaQueryWrapper<OaFjzykEntity>()
                .eq(OaFjzykEntity::getFoaid, pid));

         Map result = new HashMap();
         result.put("dy", dy);
         result.put("fjList", fjList);
        return HttpResult.ok(result);
    }


    @AutoLog(value = "环节名称集合")
    @ApiOperation(value = "环节名称集合")
    @GetMapping(value = "hjmclist")
    public HttpResult<?> hjmclist(){
        List<String> dwhjmc = OaFlowConstant.dwhjmc();
        return HttpResult.ok(dwhjmc);
    }

    @AutoLog(value = "发起入党申请")
    @ApiOperation(value = "发起入党申请")
    @PostMapping(value = "initBzFlow")
    public HttpResult<?> initBzFlow(@RequestBody PartyRsDyrdsqjl partyRsDyrdsqjl) {
        String oaid = "";
        //当前人的id
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        if (currentUser == null) {
            return HttpResult.error("当前登录已失效，请重新登录");
        }

        if (StringUtils.isNotBlank(partyRsDyrdsqjl.getId())){
            PartyRsDyrdsqjl rdsq = partyRsDyrdsqjlService.getById(partyRsDyrdsqjl.getId());

            ConvertUtils.register(new DateConvert(), Date.class);
            try {
                BeanUtils.populate(rdsq, BeanUtils.describe(partyRsDyrdsqjl));
            } catch (IllegalAccessException e) {
                log.error("出错-保存事项【非法访问异常】,{}", e.getMessage());
            } catch (InvocationTargetException e) {
                log.error("出错-保存事项【调用TargetException】,{}", e.getMessage());
            } catch (NoSuchMethodException e) {
                log.error("出错-找不到可用方法", e.getMessage());
            }
            oaid = partyRsDyrdsqjl.getId();
            rdsq.setFuserid(currentUser.getId());
            rdsq.setFxm(currentUser.getName());
            partyRsDyrdsqjlService.updateById(rdsq);
        }else {
            oaid = GetUuIdUtils.ReplaceUuId();

            partyRsDyrdsqjl.setId(oaid);
            partyRsDyrdsqjl.setFuserid(currentUser.getId());
            partyRsDyrdsqjl.setFxm(currentUser.getName());
            partyRsDyrdsqjl.setFlczt(OaFlowNodeConstant.HJMC_LCZB);

            partyRsDyrdsqjlService.save(partyRsDyrdsqjl);
        }

        String msg = "保存成功";
        String lcmbCode = OaFlowConstant.FZPARTYWORKFLOW;
        OaJobEntity job = new OaJobEntity();
        // 初始化流程
        Result result = newPartyRsDyrdsqjlFlowService.createProcess(lcmbCode,oaid, currentUser,OaFlowConstant.DF_HJ_BLSX_HOURS);

        //做一次规则校验 如果查到此oaid 在表中已经插入 那就执行更新
        PartyRsDyrdsqjl partyRsDyrdsqjl1 = partyRsDyrdsqjlService.getById(oaid);
        List<OaProcessBusiness> oaProcessBusinessList = oaProcessBusinessService.list(new LambdaQueryWrapper<OaProcessBusiness>()
                .eq(OaProcessBusiness::getFpid, oaid));

        String bt = currentUser.getName()+"提交的入党申请"; //标题
        String zy = "申请时间:["+ DateConversionUtils.DateToYMDHMSChineseString(new Date()) +"]"+"\n";
        if (oaProcessBusinessList.size() == 0){
            //初始化的时候 像 流程业务主表添加拼接初始化数据
            oaProcessBusinessService.addProcess(oaid,zy,bt,lcmbCode,OaFlowConstant.DF);
        }else {
            String id = oaProcessBusinessList.get(0).getId();  // 当前已经插入的主键id然后更新 摘要信息
            OaProcessBusiness oaProcessBusiness = oaProcessBusinessService.getById(id);
            oaProcessBusiness.setFzy(zy);
            oaProcessBusinessService.updateById(oaProcessBusiness);
        }

        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }else {
            job = (OaJobEntity)result.getResult();
            if (job != null) {
                // 是否提交流程
                if(StringUtils.isBlank(oaid)){
                    return HttpResult.error("参数丢失");
                }
                String nextNodeId = "";
                String nextNodeDbrId = "";
                if (StringUtils.isNotBlank(partyRsDyrdsqjl.getFsffqlc()) && partyRsDyrdsqjl.getFsffqlc().equals(OaCommonFlowConstant.SFFQLC_YES)) {

                    if (StringUtils.isBlank(partyRsDyrdsqjl.getFlczt())) {
                        partyRsDyrdsqjl.setFlczt(OaFlowNodeConstant.HJMC_LCZB);
                    }
                    Result result1 = newPartyRsDyrdsqjlFlowService.passJob(oaid,job.getId(),"同意", nextNodeId, nextNodeDbrId, OaFlowConstant.DF_HJ_BLSX_HOURS, "");
                    if (!result1.isSuccess()) {
                        return HttpResult.error(result.getMessage());
                    }
                    msg = "提交成功";

                    //提交完成后 更新通知信息
                    sysTzMessageService.tjMessage(oaid);

                    List<OaProcessBusiness> oaProcessBusinessList1 = oaProcessBusinessService.list(new LambdaQueryWrapper<OaProcessBusiness>()
                            .eq(OaProcessBusiness::getFpid, oaid));
                    OaProcessBusiness oaProcessBusiness = oaProcessBusinessList1.get(0);
                    OaProcessBusiness byId1 = oaProcessBusinessService.getById(oaProcessBusiness.getId());
                    byId1.setFsfkch(0);
                    byId1.setFcshdb(OaFlowConstant.FLOW_BLZT_YB);
                    oaProcessBusinessService.updateById(byId1);
                }
            }
        }

        HashMap map = new HashMap();
        map.put("msg",msg);
        map.put("DwMap",partyRsDyrdsqjl);
        map.put("jobMap",job);

        return HttpResult.ok(map);
    }

    /**
     * 党务-入党申请保存接口
     */
    @AutoLog(value = " 党务-入党申请保存接口")
    @ApiOperation(value = " 党务-入党申请保存接口")
    @PostMapping(value = "/saveFlow")
    public HttpResult<?> saveFlow(@RequestBody DyFlowVo dyFlowVo) {
        String submitType = OaCommonFlowConstant.SUBMIT_TYPE_SAVE; // 保存
        String jobId = dyFlowVo.getJobid(); // 当前流程任务id
        String oaid = dyFlowVo.getOaid(); // 当前办公主键id
        String opinion = dyFlowVo.getOpinion(); // 办理意见
        if (StringUtils.isBlank(jobId)){
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }
        // 流程处理
        Result httpResult = newPartyRsDyrdsqjlFlowService.handleFlow(dyFlowVo, null, jobId, oaid, submitType, opinion);
        if (!httpResult.isSuccess()){
            return HttpResult.error(httpResult.getMessage());
        }
        Map map = new HashMap();
        HttpResult<Object> res = new HttpResult<>(true);
        res.setMessage("保存成功");
        res.setResult(map);
        return res;
    }

    @AutoLog(value = "党务-入党申请提交接口")
    @ApiOperation(value = "党务-入党申请提交接口")
    @PostMapping(value = "/submitFlow")
    public HttpResult<?> submitFlow(@RequestBody DyFlowVo dyFlowVo) {

        String submitType = OaCommonFlowConstant.SUBMIT_TYPE_SUBMIT; // 提交

        String jobId = dyFlowVo.getJobid();
        String oaid = dyFlowVo.getOaid();
        String opinion = dyFlowVo.getOpinion();

        PartyRsDyrdsqjl oaId = partyRsDyrdsqjlService.getById(oaid);
        if (oaId == null){
            throw new BusinessException("没有相匹配的数据！");
        }

        OaJobEntity nowJob = spcySqsxJobService.getById(jobId);
        if (nowJob == null){
            throw new BusinessException("没有相匹配的流程任务！");
        }
        if (StringUtils.isBlank(dyFlowVo.getLcmbCode())){
            dyFlowVo.setLcmbCode(OaFlowConstant.FZPARTYWORKFLOW);
        }


        if (!nowJob.getFhjmc().equals(OaFlowConstant.DF_HJMC_CLGD25)) {
            oaId.setFlczt(OaCommonFlowConstant.FLOW_LCZB);
        }
        if (StringUtils.isBlank(oaId.getFsffqlc())) {
            oaId.setFsffqlc(OaCommonFlowConstant.SFFQLC_YES);
        }

        partyRsDyrdsqjlService.updateById(oaId);

        if (StringUtils.isBlank(jobId)) {
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }
        /* if (StringUtils.isBlank(opinion)){
            return HttpResult.error("请填写办理意见");2
        }*/
//        SpcySqsxJob nowJob = null;
        Result httpResult1 = newPartyRsDyrdsqjlFlowService.handleFlow(dyFlowVo, nowJob, jobId, oaid, submitType, opinion);
        if (!httpResult1.isSuccess()){
            return HttpResult.error(httpResult1.getMessage());
        }
        List<OaProcessBusiness> oaProcessBusinessList1 = oaProcessBusinessService.list(new LambdaQueryWrapper<OaProcessBusiness>()
                .eq(OaProcessBusiness::getFpid, oaid));
        OaProcessBusiness oaProcessBusiness = oaProcessBusinessList1.get(0);
        OaProcessBusiness byId1 = oaProcessBusinessService.getById(oaProcessBusiness.getId());
//        byId1.setFsfkch(0);
        byId1.setFcshdb(OaFlowConstant.FLOW_BLZT_YB);
        oaProcessBusinessService.updateById(byId1);
        //提交完成后 更新待办信息
        sysTzMessageService.tjMessage(oaid);
//        myLcFlowService.recall(oaid);
        return HttpResult.ok("提交成功");
    }


    /**
     * 批量查询
     */
    @AutoLog(value = "批量查询")
    @ApiOperation(value = "批量查询")
    @ApiImplicitParam(value = "jobids", name = "jobids", required = true)
    @GetMapping(value = "queryBatchJobByJobIds")
    public HttpResult<?> queryBatchJobByJobIds(@RequestParam("jobids")String jobids) {
        if (StringUtils.isBlank(jobids)) {
            return HttpResult.error("参数不能为空,请选择数据");
        }
        List<Map> mapList = new ArrayList<>();
        List<String> jobidsList = Arrays.asList(jobids.split(","));
        if (CollectionUtils.isNotEmpty(jobidsList)) {
            for (String jobid : jobidsList){
                mapList.add(newPartyRsDyrdsqjlFlowService.getJobConcernByJobId(jobid));
            }
        }
        return HttpResult.ok(mapList);
    }

    /**
     * 查询当前流程任务详情-通过当前流程任务id
     */
    @AutoLog(value = "查询当前流程任务详情-通过当前流程任务id")
    @ApiOperation(value = "查询当前流程任务详情-通过当前流程任务id")
    @ApiImplicitParam(value = "jobid", name = "流程任务id", required = true)
    @GetMapping(value = "queryJobByJobId")
    public HttpResult<?> queryJobByJobId(@RequestParam("jobid") String jobid) {
        if (StringUtils.isBlank(jobid)) {
            return HttpResult.error("流程任务id不能为空");
        }
        Map map = newPartyRsDyrdsqjlFlowService.getJobConcernByJobId(jobid);
        return HttpResult.ok(map);
    }

    /**
     * 获取已办列表-通过当前流程id-自定义退回
     *
     * @param jobid
     * @return
     */
    @AutoLog(value = "获取已办列表-通过当前流程id-自定义退回")
    @ApiOperation(value = "获取已办列表-通过当前流程id-自定义退回")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobid", value = "流程任务id"),
            @ApiImplicitParam(name = "isZdhj", value = "是否指定环节，默认：true，指定")
    })
    @GetMapping(value = "queryAllYbJob")
    public HttpResult<?> queryAllYbJob(@RequestParam(value = "jobid", defaultValue = "") String jobid,
                                       @RequestParam(value = "isZdhj", defaultValue = "true") boolean isZdhj) {
        List<Map<String, String>> currentJobPrevious = newPartyRsDyrdsqjlFlowService.getCurrentJobPrevious(jobid, isZdhj);
        return HttpResult.ok(currentJobPrevious);
    }

    /**
     * 退回环节
     *
     * @return
     */
    @AutoLog(value = "自定义-退回环节")
    @ApiOperation(value = "自定义-退回环节")
    @PostMapping(value = "returnUpperzdyFlowJob")
    public HttpResult<?> returnUpperzdyFlowJob(@RequestBody OaReturnVo oaReturnVo) {
        newPartyRsDyrdsqjlFlowService.returnZdJob(oaReturnVo);
        OaJobEntity oaJobEntity = spcySqsxJobService.getById(oaReturnVo.getJobid());
        OaJobEntity thjob = spcySqsxJobService.getById(oaReturnVo.getShjid());

        PartyRsDyrdsqjl nkRsBxlc = partyRsDyrdsqjlService.getById(oaJobEntity.getFpid());

        //退回更新通知信息

        String fpid = oaJobEntity.getFpid();
        sysTzMessageService.endMessage(fpid,false,false,true);

        return HttpResult.ok("退回成功");
    }

    @AutoLog(value = "删除入党申请")
    @ApiOperation(value = "删除入党申请")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobids",value = "流程任务id,逗号分割",required = true)
    })
    @DeleteMapping(value = "deleteLgqsFlowJob")
    public HttpResult<?> deleteLgqsFlowJob(@RequestParam(value = "jobids") String jobids){
        if (StringUtils.isBlank(jobids)){
            return HttpResult.error("参数不能为空");
        }
        List<String> jobIdList = Arrays.asList(jobids.split(","));
        String logNr = "";
        Map<String, Object> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(jobIdList)){
            List<OaJobEntity> jobList = spcySqsxJobService.listByIds(jobIdList);
            if (CollectionUtils.isNotEmpty(jobList)){
                for (OaJobEntity job : jobList) {
                    spcySqsxJobService.removeById(job.getId());
                    PartyRsDyrdsqjl nkRsYstpsq = partyRsDyrdsqjlService.getById(job.getFpid());
                    if (nkRsYstpsq != null) {

                        partyRsDyrdsqjlService.removeById(job.getFpid());
                        newPartyRsDyrdsqjlFlowService.delJbxxFzgc(job.getFpid());

                        logNr = "删除入党申请" + job.getFhjmc() + ": ";
                        map = ObjectToMapUtils.objectToMap(nkRsYstpsq);
                        logNr += LogUtils.MapToStringMethod(map);

                        spcyLogService.addLogs(job.getFhjmc(), logNr, job.getFpid(), OaFlowConstant.FZPARTYWORKFLOW, OaCommonFlowConstant.LOGS_SYS_TYPE_SC);
                    }
                }
            }
        }

        return HttpResult.ok("删除成功");
    }

}
